home *** CD-ROM | disk | FTP | other *** search
/ PCGUIA 127 / PC Guia 127.iso / Software / Produtividade / OpenOffice.org 2.0.1 / openofficeorg3.cab / doctest.py < prev    next >
Text File  |  2005-11-19  |  51KB  |  1,506 lines

  1. # Module doctest.
  2. # Released to the public domain 16-Jan-2001,
  3. # by Tim Peters (tim.one@home.com).
  4.  
  5. # Provided as-is; use at your own risk; no warranty; no promises; enjoy!
  6.  
  7. """Module doctest -- a framework for running examples in docstrings.
  8.  
  9. NORMAL USAGE
  10.  
  11. In normal use, end each module M with:
  12.  
  13. def _test():
  14.     import doctest, M           # replace M with your module's name
  15.     return doctest.testmod(M)   # ditto
  16.  
  17. if __name__ == "__main__":
  18.     _test()
  19.  
  20. Then running the module as a script will cause the examples in the
  21. docstrings to get executed and verified:
  22.  
  23. python M.py
  24.  
  25. This won't display anything unless an example fails, in which case the
  26. failing example(s) and the cause(s) of the failure(s) are printed to stdout
  27. (why not stderr? because stderr is a lame hack <0.2 wink>), and the final
  28. line of output is "Test failed.".
  29.  
  30. Run it with the -v switch instead:
  31.  
  32. python M.py -v
  33.  
  34. and a detailed report of all examples tried is printed to stdout, along
  35. with assorted summaries at the end.
  36.  
  37. You can force verbose mode by passing "verbose=1" to testmod, or prohibit
  38. it by passing "verbose=0".  In either of those cases, sys.argv is not
  39. examined by testmod.
  40.  
  41. In any case, testmod returns a 2-tuple of ints (f, t), where f is the
  42. number of docstring examples that failed and t is the total number of
  43. docstring examples attempted.
  44.  
  45.  
  46. WHICH DOCSTRINGS ARE EXAMINED?
  47.  
  48. + M.__doc__.
  49.  
  50. + f.__doc__ for all functions f in M.__dict__.values(), except those
  51.   defined in other modules.
  52.  
  53. + C.__doc__ for all classes C in M.__dict__.values(), except those
  54.   defined in other modules.
  55.  
  56. + If M.__test__ exists and "is true", it must be a dict, and
  57.   each entry maps a (string) name to a function object, class object, or
  58.   string.  Function and class object docstrings found from M.__test__
  59.   are searched even if the name is private, and strings are searched
  60.   directly as if they were docstrings.  In output, a key K in M.__test__
  61.   appears with name
  62.       <name of M>.__test__.K
  63.  
  64. Any classes found are recursively searched similarly, to test docstrings in
  65. their contained methods and nested classes.  All names reached from
  66. M.__test__ are searched.
  67.  
  68. Optionally, functions with private names can be skipped (unless listed in
  69. M.__test__) by supplying a function to the "isprivate" argument that will
  70. identify private functions.  For convenience, one such function is
  71. supplied.  docttest.is_private considers a name to be private if it begins
  72. with an underscore (like "_my_func") but doesn't both begin and end with
  73. (at least) two underscores (like "__init__").  By supplying this function
  74. or your own "isprivate" function to testmod, the behavior can be customized.
  75.  
  76. If you want to test docstrings in objects with private names too, stuff
  77. them into an M.__test__ dict, or see ADVANCED USAGE below (e.g., pass your
  78. own isprivate function to Tester's constructor, or call the rundoc method
  79. of a Tester instance).
  80.  
  81. WHAT'S THE EXECUTION CONTEXT?
  82.  
  83. By default, each time testmod finds a docstring to test, it uses a *copy*
  84. of M's globals (so that running tests on a module doesn't change the
  85. module's real globals, and so that one test in M can't leave behind crumbs
  86. that accidentally allow another test to work).  This means examples can
  87. freely use any names defined at top-level in M.  It also means that sloppy
  88. imports (see above) can cause examples in external docstrings to use
  89. globals inappropriate for them.
  90.  
  91. You can force use of your own dict as the execution context by passing
  92. "globs=your_dict" to testmod instead.  Presumably this would be a copy of
  93. M.__dict__ merged with the globals from other imported modules.
  94.  
  95.  
  96. WHAT IF I WANT TO TEST A WHOLE PACKAGE?
  97.  
  98. Piece o' cake, provided the modules do their testing from docstrings.
  99. Here's the test.py I use for the world's most elaborate Rational/
  100. floating-base-conversion pkg (which I'll distribute some day):
  101.  
  102. from Rational import Cvt
  103. from Rational import Format
  104. from Rational import machprec
  105. from Rational import Rat
  106. from Rational import Round
  107. from Rational import utils
  108.  
  109. modules = (Cvt,
  110.            Format,
  111.            machprec,
  112.            Rat,
  113.            Round,
  114.            utils)
  115.  
  116. def _test():
  117.     import doctest
  118.     import sys
  119.     verbose = "-v" in sys.argv
  120.     for mod in modules:
  121.         doctest.testmod(mod, verbose=verbose, report=0)
  122.     doctest.master.summarize()
  123.  
  124. if __name__ == "__main__":
  125.     _test()
  126.  
  127. IOW, it just runs testmod on all the pkg modules.  testmod remembers the
  128. names and outcomes (# of failures, # of tries) for each item it's seen, and
  129. passing "report=0" prevents it from printing a summary in verbose mode.
  130. Instead, the summary is delayed until all modules have been tested, and
  131. then "doctest.master.summarize()" forces the summary at the end.
  132.  
  133. So this is very nice in practice:  each module can be tested individually
  134. with almost no work beyond writing up docstring examples, and collections
  135. of modules can be tested too as a unit with no more work than the above.
  136.  
  137.  
  138. WHAT ABOUT EXCEPTIONS?
  139.  
  140. No problem, as long as the only output generated by the example is the
  141. traceback itself.  For example:
  142.  
  143.     >>> [1, 2, 3].remove(42)
  144.     Traceback (most recent call last):
  145.       File "<stdin>", line 1, in ?
  146.     ValueError: list.remove(x): x not in list
  147.     >>>
  148.  
  149. Note that only the exception type and value are compared (specifically,
  150. only the last line in the traceback).
  151.  
  152.  
  153. ADVANCED USAGE
  154.  
  155. doctest.testmod() captures the testing policy I find most useful most
  156. often.  You may want other policies.
  157.  
  158. testmod() actually creates a local instance of class doctest.Tester, runs
  159. appropriate methods of that class, and merges the results into global
  160. Tester instance doctest.master.
  161.  
  162. You can create your own instances of doctest.Tester, and so build your own
  163. policies, or even run methods of doctest.master directly.  See
  164. doctest.Tester.__doc__ for details.
  165.  
  166.  
  167. SO WHAT DOES A DOCSTRING EXAMPLE LOOK LIKE ALREADY!?
  168.  
  169. Oh ya.  It's easy!  In most cases a copy-and-paste of an interactive
  170. console session works fine -- just make sure the leading whitespace is
  171. rigidly consistent (you can mix tabs and spaces if you're too lazy to do it
  172. right, but doctest is not in the business of guessing what you think a tab
  173. means).
  174.  
  175.     >>> # comments are ignored
  176.     >>> x = 12
  177.     >>> x
  178.     12
  179.     >>> if x == 13:
  180.     ...     print "yes"
  181.     ... else:
  182.     ...     print "no"
  183.     ...     print "NO"
  184.     ...     print "NO!!!"
  185.     ...
  186.     no
  187.     NO
  188.     NO!!!
  189.     >>>
  190.  
  191. Any expected output must immediately follow the final ">>>" or "..." line
  192. containing the code, and the expected output (if any) extends to the next
  193. ">>>" or all-whitespace line.  That's it.
  194.  
  195. Bummers:
  196.  
  197. + Expected output cannot contain an all-whitespace line, since such a line
  198.   is taken to signal the end of expected output.
  199.  
  200. + Output to stdout is captured, but not output to stderr (exception
  201.   tracebacks are captured via a different means).
  202.  
  203. + If you continue a line via backslashing in an interactive session, or for
  204.   any other reason use a backslash, you need to double the backslash in the
  205.   docstring version.  This is simply because you're in a string, and so the
  206.   backslash must be escaped for it to survive intact.  Like:
  207.  
  208. >>> if "yes" == \\
  209. ...     "y" +   \\
  210. ...     "es":   # in the source code you'll see the doubled backslashes
  211. ...     print 'yes'
  212. yes
  213.  
  214. The starting column doesn't matter:
  215.  
  216. >>> assert "Easy!"
  217.      >>> import math
  218.             >>> math.floor(1.9)
  219.             1.0
  220.  
  221. and as many leading whitespace characters are stripped from the expected
  222. output as appeared in the initial ">>>" line that triggered it.
  223.  
  224. If you execute this very file, the examples above will be found and
  225. executed, leading to this output in verbose mode:
  226.  
  227. Running doctest.__doc__
  228. Trying: [1, 2, 3].remove(42)
  229. Expecting:
  230. Traceback (most recent call last):
  231.   File "<stdin>", line 1, in ?
  232. ValueError: list.remove(x): x not in list
  233. ok
  234. Trying: x = 12
  235. Expecting: nothing
  236. ok
  237. Trying: x
  238. Expecting: 12
  239. ok
  240. Trying:
  241. if x == 13:
  242.     print "yes"
  243. else:
  244.     print "no"
  245.     print "NO"
  246.     print "NO!!!"
  247. Expecting:
  248. no
  249. NO
  250. NO!!!
  251. ok
  252. ... and a bunch more like that, with this summary at the end:
  253.  
  254. 5 items had no tests:
  255.     doctest.Tester.__init__
  256.     doctest.Tester.run__test__
  257.     doctest.Tester.summarize
  258.     doctest.run_docstring_examples
  259.     doctest.testmod
  260. 12 items passed all tests:
  261.    8 tests in doctest
  262.    6 tests in doctest.Tester
  263.   10 tests in doctest.Tester.merge
  264.   14 tests in doctest.Tester.rundict
  265.    3 tests in doctest.Tester.rundoc
  266.    3 tests in doctest.Tester.runstring
  267.    2 tests in doctest.__test__._TestClass
  268.    2 tests in doctest.__test__._TestClass.__init__
  269.    2 tests in doctest.__test__._TestClass.get
  270.    1 tests in doctest.__test__._TestClass.square
  271.    2 tests in doctest.__test__.string
  272.    7 tests in doctest.is_private
  273. 60 tests in 17 items.
  274. 60 passed and 0 failed.
  275. Test passed.
  276. """
  277.  
  278. __all__ = [
  279.     'testmod',
  280.     'run_docstring_examples',
  281.     'is_private',
  282.     'Tester',
  283.     'DocTestTestFailure',
  284.     'DocTestSuite',
  285.     'testsource',
  286.     'debug',
  287.     'master',
  288. ]
  289.  
  290. import __future__
  291.  
  292. import re
  293. PS1 = ">>>"
  294. PS2 = "..."
  295. _isPS1 = re.compile(r"(\s*)" + re.escape(PS1)).match
  296. _isPS2 = re.compile(r"(\s*)" + re.escape(PS2)).match
  297. _isEmpty = re.compile(r"\s*$").match
  298. _isComment = re.compile(r"\s*#").match
  299. del re
  300.  
  301. from types import StringTypes as _StringTypes
  302.  
  303. from inspect import isclass    as _isclass
  304. from inspect import isfunction as _isfunction
  305. from inspect import ismethod as _ismethod
  306. from inspect import ismodule   as _ismodule
  307. from inspect import classify_class_attrs as _classify_class_attrs
  308.  
  309. # Option constants.
  310. DONT_ACCEPT_TRUE_FOR_1 = 1 << 0
  311.  
  312. # Extract interactive examples from a string.  Return a list of triples,
  313. # (source, outcome, lineno).  "source" is the source code, and ends
  314. # with a newline iff the source spans more than one line.  "outcome" is
  315. # the expected output if any, else an empty string.  When not empty,
  316. # outcome always ends with a newline.  "lineno" is the line number,
  317. # 0-based wrt the start of the string, of the first source line.
  318.  
  319. def _extract_examples(s):
  320.     isPS1, isPS2 = _isPS1, _isPS2
  321.     isEmpty, isComment = _isEmpty, _isComment
  322.     examples = []
  323.     lines = s.split("\n")
  324.     i, n = 0, len(lines)
  325.     while i < n:
  326.         line = lines[i]
  327.         i = i + 1
  328.         m = isPS1(line)
  329.         if m is None:
  330.             continue
  331.         j = m.end(0)  # beyond the prompt
  332.         if isEmpty(line, j) or isComment(line, j):
  333.             # a bare prompt or comment -- not interesting
  334.             continue
  335.         lineno = i - 1
  336.         if line[j] != " ":
  337.             raise ValueError("line " + `lineno` + " of docstring lacks "
  338.                 "blank after " + PS1 + ": " + line)
  339.         j = j + 1
  340.         blanks = m.group(1)
  341.         nblanks = len(blanks)
  342.         # suck up this and following PS2 lines
  343.         source = []
  344.         while 1:
  345.             source.append(line[j:])
  346.             line = lines[i]
  347.             m = isPS2(line)
  348.             if m:
  349.                 if m.group(1) != blanks:
  350.                     raise ValueError("inconsistent leading whitespace "
  351.                         "in line " + `i` + " of docstring: " + line)
  352.                 i = i + 1
  353.             else:
  354.                 break
  355.         if len(source) == 1:
  356.             source = source[0]
  357.         else:
  358.             # get rid of useless null line from trailing empty "..."
  359.             if source[-1] == "":
  360.                 del source[-1]
  361.             source = "\n".join(source) + "\n"
  362.         # suck up response
  363.         if isPS1(line) or isEmpty(line):
  364.             expect = ""
  365.         else:
  366.             expect = []
  367.             while 1:
  368.                 if line[:nblanks] != blanks:
  369.                     raise ValueError("inconsistent leading whitespace "
  370.                         "in line " + `i` + " of docstring: " + line)
  371.                 expect.append(line[nblanks:])
  372.                 i = i + 1
  373.                 line = lines[i]
  374.                 if isPS1(line) or isEmpty(line):
  375.                     break
  376.             expect = "\n".join(expect) + "\n"
  377.         examples.append( (source, expect, lineno) )
  378.     return examples
  379.  
  380. # Capture stdout when running examples.
  381.  
  382. class _SpoofOut:
  383.     def __init__(self):
  384.         self.clear()
  385.     def write(self, s):
  386.         self.buf.append(s)
  387.     def get(self):
  388.         guts = "".join(self.buf)
  389.         # If anything at all was written, make sure there's a trailing
  390.         # newline.  There's no way for the expected output to indicate
  391.         # that a trailing newline is missing.
  392.         if guts and not guts.endswith("\n"):
  393.             guts = guts + "\n"
  394.         # Prevent softspace from screwing up the next test case, in
  395.         # case they used print with a trailing comma in an example.
  396.         if hasattr(self, "softspace"):
  397.             del self.softspace
  398.         return guts
  399.     def clear(self):
  400.         self.buf = []
  401.         if hasattr(self, "softspace"):
  402.             del self.softspace
  403.     def flush(self):
  404.         # JPython calls flush
  405.         pass
  406.  
  407. # Display some tag-and-msg pairs nicely, keeping the tag and its msg
  408. # on the same line when that makes sense.
  409.  
  410. def _tag_out(printer, *tag_msg_pairs):
  411.     for tag, msg in tag_msg_pairs:
  412.         printer(tag + ":")
  413.         msg_has_nl = msg[-1:] == "\n"
  414.         msg_has_two_nl = msg_has_nl and \
  415.                         msg.find("\n") < len(msg) - 1
  416.         if len(tag) + len(msg) < 76 and not msg_has_two_nl:
  417.             printer(" ")
  418.         else:
  419.             printer("\n")
  420.         printer(msg)
  421.         if not msg_has_nl:
  422.             printer("\n")
  423.  
  424. # Run list of examples, in context globs.  "out" can be used to display
  425. # stuff to "the real" stdout, and fakeout is an instance of _SpoofOut
  426. # that captures the examples' std output.  Return (#failures, #tries).
  427.  
  428. def _run_examples_inner(out, fakeout, examples, globs, verbose, name,
  429.                         compileflags, optionflags):
  430.     import sys, traceback
  431.     OK, BOOM, FAIL = range(3)
  432.     NADA = "nothing"
  433.     stderr = _SpoofOut()
  434.     failures = 0
  435.     for source, want, lineno in examples:
  436.         if verbose:
  437.             _tag_out(out, ("Trying", source),
  438.                           ("Expecting", want or NADA))
  439.         fakeout.clear()
  440.         try:
  441.             exec compile(source, "<string>", "single",
  442.                          compileflags, 1) in globs
  443.             got = fakeout.get()
  444.             state = OK
  445.         except KeyboardInterrupt:
  446.             raise
  447.         except:
  448.             # See whether the exception was expected.
  449.             if want.find("Traceback (innermost last):\n") == 0 or \
  450.                want.find("Traceback (most recent call last):\n") == 0:
  451.                 # Only compare exception type and value - the rest of
  452.                 # the traceback isn't necessary.
  453.                 want = want.split('\n')[-2] + '\n'
  454.                 exc_type, exc_val = sys.exc_info()[:2]
  455.                 got = traceback.format_exception_only(exc_type, exc_val)[-1]
  456.                 state = OK
  457.             else:
  458.                 # unexpected exception
  459.                 stderr.clear()
  460.                 traceback.print_exc(file=stderr)
  461.                 state = BOOM
  462.  
  463.         if state == OK:
  464.             if (got == want or
  465.                 (not (optionflags & DONT_ACCEPT_TRUE_FOR_1) and
  466.                  (got, want) in (("True\n", "1\n"), ("False\n", "0\n"))
  467.                 )
  468.                ):
  469.                 if verbose:
  470.                     out("ok\n")
  471.                 continue
  472.             state = FAIL
  473.  
  474.         assert state in (FAIL, BOOM)
  475.         failures = failures + 1
  476.         out("*" * 65 + "\n")
  477.         _tag_out(out, ("Failure in example", source))
  478.         out("from line #" + `lineno` + " of " + name + "\n")
  479.         if state == FAIL:
  480.             _tag_out(out, ("Expected", want or NADA), ("Got", got))
  481.         else:
  482.             assert state == BOOM
  483.             _tag_out(out, ("Exception raised", stderr.get()))
  484.  
  485.     return failures, len(examples)
  486.  
  487. # Get the future-flags associated with the future features that have been
  488. # imported into globs.
  489.  
  490. def _extract_future_flags(globs):
  491.     flags = 0
  492.     for fname in __future__.all_feature_names:
  493.         feature = globs.get(fname, None)
  494.         if feature is getattr(__future__, fname):
  495.             flags |= feature.compiler_flag
  496.     return flags
  497.  
  498. # Run list of examples, in a shallow copy of context (dict) globs.
  499. # Return (#failures, #tries).
  500.  
  501. def _run_examples(examples, globs, verbose, name, compileflags,
  502.                   optionflags):
  503.     import sys
  504.     saveout = sys.stdout
  505.     globs = globs.copy()
  506.     try:
  507.         sys.stdout = fakeout = _SpoofOut()
  508.         x = _run_examples_inner(saveout.write, fakeout, examples,
  509.                                 globs, verbose, name, compileflags,
  510.                                 optionflags)
  511.     finally:
  512.         sys.stdout = saveout
  513.         # While Python gc can clean up most cycles on its own, it doesn't
  514.         # chase frame objects.  This is especially irksome when running
  515.         # generator tests that raise exceptions, because a named generator-
  516.         # iterator gets an entry in globs, and the generator-iterator
  517.         # object's frame's traceback info points back to globs.  This is
  518.         # easy to break just by clearing the namespace.  This can also
  519.         # help to break other kinds of cycles, and even for cycles that
  520.         # gc can break itself it's better to break them ASAP.
  521.         globs.clear()
  522.     return x
  523.  
  524. def run_docstring_examples(f, globs, verbose=0, name="NoName",
  525.                            compileflags=None, optionflags=0):
  526.     """f, globs, verbose=0, name="NoName" -> run examples from f.__doc__.
  527.  
  528.     Use (a shallow copy of) dict globs as the globals for execution.
  529.     Return (#failures, #tries).
  530.  
  531.     If optional arg verbose is true, print stuff even if there are no
  532.     failures.
  533.     Use string name in failure msgs.
  534.     """
  535.  
  536.     try:
  537.         doc = f.__doc__
  538.         if not doc:
  539.             # docstring empty or None
  540.             return 0, 0
  541.         # just in case CT invents a doc object that has to be forced
  542.         # to look like a string <0.9 wink>
  543.         doc = str(doc)
  544.     except KeyboardInterrupt:
  545.         raise
  546.     except:
  547.         return 0, 0
  548.  
  549.     e = _extract_examples(doc)
  550.     if not e:
  551.         return 0, 0
  552.     if compileflags is None:
  553.         compileflags = _extract_future_flags(globs)
  554.     return _run_examples(e, globs, verbose, name, compileflags, optionflags)
  555.  
  556. def is_private(prefix, base):
  557.     """prefix, base -> true iff name prefix + "." + base is "private".
  558.  
  559.     Prefix may be an empty string, and base does not contain a period.
  560.     Prefix is ignored (although functions you write conforming to this
  561.     protocol may make use of it).
  562.     Return true iff base begins with an (at least one) underscore, but
  563.     does not both begin and end with (at least) two underscores.
  564.  
  565.     >>> is_private("a.b", "my_func")
  566.     False
  567.     >>> is_private("____", "_my_func")
  568.     True
  569.     >>> is_private("someclass", "__init__")
  570.     False
  571.     >>> is_private("sometypo", "__init_")
  572.     True
  573.     >>> is_private("x.y.z", "_")
  574.     True
  575.     >>> is_private("_x.y.z", "__")
  576.     False
  577.     >>> is_private("", "")  # senseless but consistent
  578.     False
  579.     """
  580.  
  581.     return base[:1] == "_" and not base[:2] == "__" == base[-2:]
  582.  
  583. # Determine if a class of function was defined in the given module.
  584.  
  585. def _from_module(module, object):
  586.     if _isfunction(object):
  587.         return module.__dict__ is object.func_globals
  588.     if _isclass(object):
  589.         return module.__name__ == object.__module__
  590.     raise ValueError("object must be a class or function")
  591.  
  592. class Tester:
  593.     """Class Tester -- runs docstring examples and accumulates stats.
  594.  
  595. In normal use, function doctest.testmod() hides all this from you,
  596. so use that if you can.  Create your own instances of Tester to do
  597. fancier things.
  598.  
  599. Methods:
  600.     runstring(s, name)
  601.         Search string s for examples to run; use name for logging.
  602.         Return (#failures, #tries).
  603.  
  604.     rundoc(object, name=None)
  605.         Search object.__doc__ for examples to run; use name (or
  606.         object.__name__) for logging.  Return (#failures, #tries).
  607.  
  608.     rundict(d, name, module=None)
  609.         Search for examples in docstrings in all of d.values(); use name
  610.         for logging.  Exclude functions and classes not defined in module
  611.         if specified.  Return (#failures, #tries).
  612.  
  613.     run__test__(d, name)
  614.         Treat dict d like module.__test__.  Return (#failures, #tries).
  615.  
  616.     summarize(verbose=None)
  617.         Display summary of testing results, to stdout.  Return
  618.         (#failures, #tries).
  619.  
  620.     merge(other)
  621.         Merge in the test results from Tester instance "other".
  622.  
  623. >>> from doctest import Tester
  624. >>> t = Tester(globs={'x': 42}, verbose=0)
  625. >>> t.runstring(r'''
  626. ...      >>> x = x * 2
  627. ...      >>> print x
  628. ...      42
  629. ... ''', 'XYZ')
  630. *****************************************************************
  631. Failure in example: print x
  632. from line #2 of XYZ
  633. Expected: 42
  634. Got: 84
  635. (1, 2)
  636. >>> t.runstring(">>> x = x * 2\\n>>> print x\\n84\\n", 'example2')
  637. (0, 2)
  638. >>> t.summarize()
  639. *****************************************************************
  640. 1 items had failures:
  641.    1 of   2 in XYZ
  642. ***Test Failed*** 1 failures.
  643. (1, 4)
  644. >>> t.summarize(verbose=1)
  645. 1 items passed all tests:
  646.    2 tests in example2
  647. *****************************************************************
  648. 1 items had failures:
  649.    1 of   2 in XYZ
  650. 4 tests in 2 items.
  651. 3 passed and 1 failed.
  652. ***Test Failed*** 1 failures.
  653. (1, 4)
  654. >>>
  655. """
  656.  
  657.     def __init__(self, mod=None, globs=None, verbose=None,
  658.                  isprivate=None, optionflags=0):
  659.         """mod=None, globs=None, verbose=None, isprivate=None,
  660. optionflags=0
  661.  
  662. See doctest.__doc__ for an overview.
  663.  
  664. Optional keyword arg "mod" is a module, whose globals are used for
  665. executing examples.  If not specified, globs must be specified.
  666.  
  667. Optional keyword arg "globs" gives a dict to be used as the globals
  668. when executing examples; if not specified, use the globals from
  669. module mod.
  670.  
  671. In either case, a copy of the dict is used for each docstring
  672. examined.
  673.  
  674. Optional keyword arg "verbose" prints lots of stuff if true, only
  675. failures if false; by default, it's true iff "-v" is in sys.argv.
  676.  
  677. Optional keyword arg "isprivate" specifies a function used to determine
  678. whether a name is private.  The default function is to assume that
  679. no functions are private.  The "isprivate" arg may be set to
  680. doctest.is_private in order to skip over functions marked as private
  681. using an underscore naming convention; see its docs for details.
  682.  
  683. See doctest.testmod docs for the meaning of optionflags.
  684. """
  685.  
  686.         if mod is None and globs is None:
  687.             raise TypeError("Tester.__init__: must specify mod or globs")
  688.         if mod is not None and not _ismodule(mod):
  689.             raise TypeError("Tester.__init__: mod must be a module; " +
  690.                             `mod`)
  691.         if globs is None:
  692.             globs = mod.__dict__
  693.         self.globs = globs
  694.  
  695.         if verbose is None:
  696.             import sys
  697.             verbose = "-v" in sys.argv
  698.         self.verbose = verbose
  699.  
  700.         # By default, assume that nothing is private
  701.         if isprivate is None:
  702.             isprivate = lambda prefix, base:  0
  703.         self.isprivate = isprivate
  704.  
  705.         self.optionflags = optionflags
  706.  
  707.         self.name2ft = {}   # map name to (#failures, #trials) pair
  708.  
  709.         self.compileflags = _extract_future_flags(globs)
  710.  
  711.     def runstring(self, s, name):
  712.         """
  713.         s, name -> search string s for examples to run, logging as name.
  714.  
  715.         Use string name as the key for logging the outcome.
  716.         Return (#failures, #examples).
  717.  
  718.         >>> t = Tester(globs={}, verbose=1)
  719.         >>> test = r'''
  720.         ...    # just an example
  721.         ...    >>> x = 1 + 2
  722.         ...    >>> x
  723.         ...    3
  724.         ... '''
  725.         >>> t.runstring(test, "Example")
  726.         Running string Example
  727.         Trying: x = 1 + 2
  728.         Expecting: nothing
  729.         ok
  730.         Trying: x
  731.         Expecting: 3
  732.         ok
  733.         0 of 2 examples failed in string Example
  734.         (0, 2)
  735.         """
  736.  
  737.         if self.verbose:
  738.             print "Running string", name
  739.         f = t = 0
  740.         e = _extract_examples(s)
  741.         if e:
  742.             f, t = _run_examples(e, self.globs, self.verbose, name,
  743.                                  self.compileflags, self.optionflags)
  744.         if self.verbose:
  745.             print f, "of", t, "examples failed in string", name
  746.         self.__record_outcome(name, f, t)
  747.         return f, t
  748.  
  749.     def rundoc(self, object, name=None):
  750.         """
  751.         object, name=None -> search object.__doc__ for examples to run.
  752.  
  753.         Use optional string name as the key for logging the outcome;
  754.         by default use object.__name__.
  755.         Return (#failures, #examples).
  756.         If object is a class object, search recursively for method
  757.         docstrings too.
  758.         object.__doc__ is examined regardless of name, but if object is
  759.         a class, whether private names reached from object are searched
  760.         depends on the constructor's "isprivate" argument.
  761.  
  762.         >>> t = Tester(globs={}, verbose=0)
  763.         >>> def _f():
  764.         ...     '''Trivial docstring example.
  765.         ...     >>> assert 2 == 2
  766.         ...     '''
  767.         ...     return 32
  768.         ...
  769.         >>> t.rundoc(_f)  # expect 0 failures in 1 example
  770.         (0, 1)
  771.         """
  772.  
  773.         if name is None:
  774.             try:
  775.                 name = object.__name__
  776.             except AttributeError:
  777.                 raise ValueError("Tester.rundoc: name must be given "
  778.                     "when object.__name__ doesn't exist; " + `object`)
  779.         if self.verbose:
  780.             print "Running", name + ".__doc__"
  781.         f, t = run_docstring_examples(object, self.globs, self.verbose, name,
  782.                                       self.compileflags, self.optionflags)
  783.         if self.verbose:
  784.             print f, "of", t, "examples failed in", name + ".__doc__"
  785.         self.__record_outcome(name, f, t)
  786.         if _isclass(object):
  787.             # In 2.2, class and static methods complicate life.  Build
  788.             # a dict "that works", by hook or by crook.
  789.             d = {}
  790.             for tag, kind, homecls, value in _classify_class_attrs(object):
  791.  
  792.                 if homecls is not object:
  793.                     # Only look at names defined immediately by the class.
  794.                     continue
  795.  
  796.                 elif self.isprivate(name, tag):
  797.                     continue
  798.  
  799.                 elif kind == "method":
  800.                     # value is already a function
  801.                     d[tag] = value
  802.  
  803.                 elif kind == "static method":
  804.                     # value isn't a function, but getattr reveals one
  805.                     d[tag] = getattr(object, tag)
  806.  
  807.                 elif kind == "class method":
  808.                     # Hmm.  A classmethod object doesn't seem to reveal
  809.                     # enough.  But getattr turns it into a bound method,
  810.                     # and from there .im_func retrieves the underlying
  811.                     # function.
  812.                     d[tag] = getattr(object, tag).im_func
  813.  
  814.                 elif kind == "property":
  815.                     # The methods implementing the property have their
  816.                     # own docstrings -- but the property may have one too.
  817.                     if value.__doc__ is not None:
  818.                         d[tag] = str(value.__doc__)
  819.  
  820.                 elif kind == "data":
  821.                     # Grab nested classes.
  822.                     if _isclass(value):
  823.                         d[tag] = value
  824.  
  825.                 else:
  826.                     raise ValueError("teach doctest about %r" % kind)
  827.  
  828.             f2, t2 = self.run__test__(d, name)
  829.             f += f2
  830.             t += t2
  831.  
  832.         return f, t
  833.  
  834.     def rundict(self, d, name, module=None):
  835.         """
  836.         d, name, module=None -> search for docstring examples in d.values().
  837.  
  838.         For k, v in d.items() such that v is a function or class,
  839.         do self.rundoc(v, name + "." + k).  Whether this includes
  840.         objects with private names depends on the constructor's
  841.         "isprivate" argument.  If module is specified, functions and
  842.         classes that are not defined in module are excluded.
  843.         Return aggregate (#failures, #examples).
  844.  
  845.         Build and populate two modules with sample functions to test that
  846.         exclusion of external functions and classes works.
  847.  
  848.         >>> import new
  849.         >>> m1 = new.module('_m1')
  850.         >>> m2 = new.module('_m2')
  851.         >>> test_data = \"""
  852.         ... def _f():
  853.         ...     '''>>> assert 1 == 1
  854.         ...     '''
  855.         ... def g():
  856.         ...    '''>>> assert 2 != 1
  857.         ...    '''
  858.         ... class H:
  859.         ...    '''>>> assert 2 > 1
  860.         ...    '''
  861.         ...    def bar(self):
  862.         ...        '''>>> assert 1 < 2
  863.         ...        '''
  864.         ... \"""
  865.         >>> exec test_data in m1.__dict__
  866.         >>> exec test_data in m2.__dict__
  867.         >>> m1.__dict__.update({"f2": m2._f, "g2": m2.g, "h2": m2.H})
  868.  
  869.         Tests that objects outside m1 are excluded:
  870.  
  871.         >>> t = Tester(globs={}, verbose=0, isprivate=is_private)
  872.         >>> t.rundict(m1.__dict__, "rundict_test", m1)  # _f, f2 and g2 and h2 skipped
  873.         (0, 3)
  874.  
  875.         Again, but with the default isprivate function allowing _f:
  876.  
  877.         >>> t = Tester(globs={}, verbose=0)
  878.         >>> t.rundict(m1.__dict__, "rundict_test_pvt", m1)  # Only f2, g2 and h2 skipped
  879.         (0, 4)
  880.  
  881.         And once more, not excluding stuff outside m1:
  882.  
  883.         >>> t = Tester(globs={}, verbose=0)
  884.         >>> t.rundict(m1.__dict__, "rundict_test_pvt")  # None are skipped.
  885.         (0, 8)
  886.  
  887.         The exclusion of objects from outside the designated module is
  888.         meant to be invoked automagically by testmod.
  889.  
  890.         >>> testmod(m1, isprivate=is_private)
  891.         (0, 3)
  892.  
  893.         """
  894.  
  895.         if not hasattr(d, "items"):
  896.             raise TypeError("Tester.rundict: d must support .items(); " +
  897.                             `d`)
  898.         f = t = 0
  899.         # Run the tests by alpha order of names, for consistency in
  900.         # verbose-mode output.
  901.         names = d.keys()
  902.         names.sort()
  903.         for thisname in names:
  904.             value = d[thisname]
  905.             if _isfunction(value) or _isclass(value):
  906.                 if module and not _from_module(module, value):
  907.                     continue
  908.                 f2, t2 = self.__runone(value, name + "." + thisname)
  909.                 f = f + f2
  910.                 t = t + t2
  911.         return f, t
  912.  
  913.     def run__test__(self, d, name):
  914.         """d, name -> Treat dict d like module.__test__.
  915.  
  916.         Return (#failures, #tries).
  917.         See testmod.__doc__ for details.
  918.         """
  919.  
  920.         failures = tries = 0
  921.         prefix = name + "."
  922.         savepvt = self.isprivate
  923.         try:
  924.             self.isprivate = lambda *args: 0
  925.             # Run the tests by alpha order of names, for consistency in
  926.             # verbose-mode output.
  927.             keys = d.keys()
  928.             keys.sort()
  929.             for k in keys:
  930.                 v = d[k]
  931.                 thisname = prefix + k
  932.                 if type(v) in _StringTypes:
  933.                     f, t = self.runstring(v, thisname)
  934.                 elif _isfunction(v) or _isclass(v) or _ismethod(v):
  935.                     f, t = self.rundoc(v, thisname)
  936.                 else:
  937.                     raise TypeError("Tester.run__test__: values in "
  938.                             "dict must be strings, functions, methods, "
  939.                             "or classes; " + `v`)
  940.                 failures = failures + f
  941.                 tries = tries + t
  942.         finally:
  943.             self.isprivate = savepvt
  944.         return failures, tries
  945.  
  946.     def summarize(self, verbose=None):
  947.         """
  948.         verbose=None -> summarize results, return (#failures, #tests).
  949.  
  950.         Print summary of test results to stdout.
  951.         Optional arg 'verbose' controls how wordy this is.  By
  952.         default, use the verbose setting established by the
  953.         constructor.
  954.         """
  955.  
  956.         if verbose is None:
  957.             verbose = self.verbose
  958.         notests = []
  959.         passed = []
  960.         failed = []
  961.         totalt = totalf = 0
  962.         for x in self.name2ft.items():
  963.             name, (f, t) = x
  964.             assert f <= t
  965.             totalt = totalt + t
  966.             totalf = totalf + f
  967.             if t == 0:
  968.                 notests.append(name)
  969.             elif f == 0:
  970.                 passed.append( (name, t) )
  971.             else:
  972.                 failed.append(x)
  973.         if verbose:
  974.             if notests:
  975.                 print len(notests), "items had no tests:"
  976.                 notests.sort()
  977.                 for thing in notests:
  978.                     print "   ", thing
  979.             if passed:
  980.                 print len(passed), "items passed all tests:"
  981.                 passed.sort()
  982.                 for thing, count in passed:
  983.                     print " %3d tests in %s" % (count, thing)
  984.         if failed:
  985.             print "*" * 65
  986.             print len(failed), "items had failures:"
  987.             failed.sort()
  988.             for thing, (f, t) in failed:
  989.                 print " %3d of %3d in %s" % (f, t, thing)
  990.         if verbose:
  991.             print totalt, "tests in", len(self.name2ft), "items."
  992.             print totalt - totalf, "passed and", totalf, "failed."
  993.         if totalf:
  994.             print "***Test Failed***", totalf, "failures."
  995.         elif verbose:
  996.             print "Test passed."
  997.         return totalf, totalt
  998.  
  999.     def merge(self, other):
  1000.         """
  1001.         other -> merge in test results from the other Tester instance.
  1002.  
  1003.         If self and other both have a test result for something
  1004.         with the same name, the (#failures, #tests) results are
  1005.         summed, and a warning is printed to stdout.
  1006.  
  1007.         >>> from doctest import Tester
  1008.         >>> t1 = Tester(globs={}, verbose=0)
  1009.         >>> t1.runstring('''
  1010.         ... >>> x = 12
  1011.         ... >>> print x
  1012.         ... 12
  1013.         ... ''', "t1example")
  1014.         (0, 2)
  1015.         >>>
  1016.         >>> t2 = Tester(globs={}, verbose=0)
  1017.         >>> t2.runstring('''
  1018.         ... >>> x = 13
  1019.         ... >>> print x
  1020.         ... 13
  1021.         ... ''', "t2example")
  1022.         (0, 2)
  1023.         >>> common = ">>> assert 1 + 2 == 3\\n"
  1024.         >>> t1.runstring(common, "common")
  1025.         (0, 1)
  1026.         >>> t2.runstring(common, "common")
  1027.         (0, 1)
  1028.         >>> t1.merge(t2)
  1029.         *** Tester.merge: 'common' in both testers; summing outcomes.
  1030.         >>> t1.summarize(1)
  1031.         3 items passed all tests:
  1032.            2 tests in common
  1033.            2 tests in t1example
  1034.            2 tests in t2example
  1035.         6 tests in 3 items.
  1036.         6 passed and 0 failed.
  1037.         Test passed.
  1038.         (0, 6)
  1039.         >>>
  1040.         """
  1041.  
  1042.         d = self.name2ft
  1043.         for name, (f, t) in other.name2ft.items():
  1044.             if name in d:
  1045.                 print "*** Tester.merge: '" + name + "' in both" \
  1046.                     " testers; summing outcomes."
  1047.                 f2, t2 = d[name]
  1048.                 f = f + f2
  1049.                 t = t + t2
  1050.             d[name] = f, t
  1051.  
  1052.     def __record_outcome(self, name, f, t):
  1053.         if name in self.name2ft:
  1054.             print "*** Warning: '" + name + "' was tested before;", \
  1055.                 "summing outcomes."
  1056.             f2, t2 = self.name2ft[name]
  1057.             f = f + f2
  1058.             t = t + t2
  1059.         self.name2ft[name] = f, t
  1060.  
  1061.     def __runone(self, target, name):
  1062.         if "." in name:
  1063.             i = name.rindex(".")
  1064.             prefix, base = name[:i], name[i+1:]
  1065.         else:
  1066.             prefix, base = "", base
  1067.         if self.isprivate(prefix, base):
  1068.             return 0, 0
  1069.         return self.rundoc(target, name)
  1070.  
  1071. master = None
  1072.  
  1073. def testmod(m=None, name=None, globs=None, verbose=None, isprivate=None,
  1074.                report=True, optionflags=0):
  1075.     """m=None, name=None, globs=None, verbose=None, isprivate=None,
  1076.        report=True, optionflags=0
  1077.  
  1078.     Test examples in docstrings in functions and classes reachable
  1079.     from module m (or the current module if m is not supplied), starting
  1080.     with m.__doc__.  Unless isprivate is specified, private names
  1081.     are not skipped.
  1082.  
  1083.     Also test examples reachable from dict m.__test__ if it exists and is
  1084.     not None.  m.__dict__ maps names to functions, classes and strings;
  1085.     function and class docstrings are tested even if the name is private;
  1086.     strings are tested directly, as if they were docstrings.
  1087.  
  1088.     Return (#failures, #tests).
  1089.  
  1090.     See doctest.__doc__ for an overview.
  1091.  
  1092.     Optional keyword arg "name" gives the name of the module; by default
  1093.     use m.__name__.
  1094.  
  1095.     Optional keyword arg "globs" gives a dict to be used as the globals
  1096.     when executing examples; by default, use m.__dict__.  A copy of this
  1097.     dict is actually used for each docstring, so that each docstring's
  1098.     examples start with a clean slate.
  1099.  
  1100.     Optional keyword arg "verbose" prints lots of stuff if true, prints
  1101.     only failures if false; by default, it's true iff "-v" is in sys.argv.
  1102.  
  1103.     Optional keyword arg "isprivate" specifies a function used to
  1104.     determine whether a name is private.  The default function is
  1105.     treat all functions as public.  Optionally, "isprivate" can be
  1106.     set to doctest.is_private to skip over functions marked as private
  1107.     using the underscore naming convention; see its docs for details.
  1108.  
  1109.     Optional keyword arg "report" prints a summary at the end when true,
  1110.     else prints nothing at the end.  In verbose mode, the summary is
  1111.     detailed, else very brief (in fact, empty if all tests passed).
  1112.  
  1113.     Optional keyword arg "optionflags" or's together module constants,
  1114.     and defaults to 0.  This is new in 2.3.  Possible values:
  1115.  
  1116.         DONT_ACCEPT_TRUE_FOR_1
  1117.             By default, if an expected output block contains just "1",
  1118.             an actual output block containing just "True" is considered
  1119.             to be a match, and similarly for "0" versus "False".  When
  1120.             DONT_ACCEPT_TRUE_FOR_1 is specified, neither substitution
  1121.             is allowed.
  1122.  
  1123.     Advanced tomfoolery:  testmod runs methods of a local instance of
  1124.     class doctest.Tester, then merges the results into (or creates)
  1125.     global Tester instance doctest.master.  Methods of doctest.master
  1126.     can be called directly too, if you want to do something unusual.
  1127.     Passing report=0 to testmod is especially useful then, to delay
  1128.     displaying a summary.  Invoke doctest.master.summarize(verbose)
  1129.     when you're done fiddling.
  1130.     """
  1131.  
  1132.     global master
  1133.  
  1134.     if m is None:
  1135.         import sys
  1136.         # DWA - m will still be None if this wasn't invoked from the command
  1137.         # line, in which case the following TypeError is about as good an error
  1138.         # as we should expect
  1139.         m = sys.modules.get('__main__')
  1140.  
  1141.     if not _ismodule(m):
  1142.         raise TypeError("testmod: module required; " + `m`)
  1143.     if name is None:
  1144.         name = m.__name__
  1145.     tester = Tester(m, globs=globs, verbose=verbose, isprivate=isprivate,
  1146.                     optionflags=optionflags)
  1147.     failures, tries = tester.rundoc(m, name)
  1148.     f, t = tester.rundict(m.__dict__, name, m)
  1149.     failures += f
  1150.     tries += t
  1151.     if hasattr(m, "__test__"):
  1152.         testdict = m.__test__
  1153.         if testdict:
  1154.             if not hasattr(testdict, "items"):
  1155.                 raise TypeError("testmod: module.__test__ must support "
  1156.                                 ".items(); " + `testdict`)
  1157.             f, t = tester.run__test__(testdict, name + ".__test__")
  1158.             failures += f
  1159.             tries += t
  1160.     if report:
  1161.         tester.summarize()
  1162.     if master is None:
  1163.         master = tester
  1164.     else:
  1165.         master.merge(tester)
  1166.     return failures, tries
  1167.  
  1168. ###########################################################################
  1169. # Various doctest extensions, to make using doctest with unittest
  1170. # easier, and to help debugging when a doctest goes wrong.  Original
  1171. # code by Jim Fulton.
  1172.  
  1173. # Utilities.
  1174.  
  1175. # If module is None, return the calling module (the module that called
  1176. # the routine that called _normalize_module -- this normally won't be
  1177. # doctest!).  If module is a string, it should be the (possibly dotted)
  1178. # name of a module, and the (rightmost) module object is returned.  Else
  1179. # module is returned untouched; the intent appears to be that module is
  1180. # already a module object in this case (although this isn't checked).
  1181.  
  1182. def _normalize_module(module):
  1183.     import sys
  1184.  
  1185.     if module is None:
  1186.         # Get our caller's caller's module.
  1187.         module = sys._getframe(2).f_globals['__name__']
  1188.         module = sys.modules[module]
  1189.  
  1190.     elif isinstance(module, (str, unicode)):
  1191.         # The ["*"] at the end is a mostly meaningless incantation with
  1192.         # a crucial property:  if, e.g., module is 'a.b.c', it convinces
  1193.         # __import__ to return c instead of a.
  1194.         module = __import__(module, globals(), locals(), ["*"])
  1195.  
  1196.     return module
  1197.  
  1198. # tests is a list of (testname, docstring, filename, lineno) tuples.
  1199. # If object has a __doc__ attr, and the __doc__ attr looks like it
  1200. # contains a doctest (specifically, if it contains an instance of '>>>'),
  1201. # then tuple
  1202. #     prefix + name, object.__doc__, filename, lineno
  1203. # is appended to tests.  Else tests is left alone.
  1204. # There is no return value.
  1205.  
  1206. def _get_doctest(name, object, tests, prefix, filename='', lineno=''):
  1207.     doc = getattr(object, '__doc__', '')
  1208.     if isinstance(doc, basestring) and '>>>' in doc:
  1209.         tests.append((prefix + name, doc, filename, lineno))
  1210.  
  1211. # tests is a list of (testname, docstring, filename, lineno) tuples.
  1212. # docstrings containing doctests are appended to tests (if any are found).
  1213. # items is a dict, like a module or class dict, mapping strings to objects.
  1214. # mdict is the global dict of a "home" module -- only objects belonging
  1215. # to this module are searched for docstrings.  module is the module to
  1216. # which mdict belongs.
  1217. # prefix is a string to be prepended to an object's name when adding a
  1218. # tuple to tests.
  1219. # The objects (values) in items are examined (recursively), and doctests
  1220. # belonging to functions and classes in the home module are appended to
  1221. # tests.
  1222. # minlineno is a gimmick to try to guess the file-relative line number
  1223. # at which a doctest probably begins.
  1224.  
  1225. def _extract_doctests(items, module, mdict, tests, prefix, minlineno=0):
  1226.  
  1227.     for name, object in items:
  1228.         # Only interested in named objects.
  1229.         if not hasattr(object, '__name__'):
  1230.             continue
  1231.  
  1232.         elif hasattr(object, 'func_globals'):
  1233.             # Looks like a function.
  1234.             if object.func_globals is not mdict:
  1235.                 # Non-local function.
  1236.                 continue
  1237.             code = getattr(object, 'func_code', None)
  1238.             filename = getattr(code, 'co_filename', '')
  1239.             lineno = getattr(code, 'co_firstlineno', -1) + 1
  1240.             if minlineno:
  1241.                 minlineno = min(lineno, minlineno)
  1242.             else:
  1243.                 minlineno = lineno
  1244.             _get_doctest(name, object, tests, prefix, filename, lineno)
  1245.  
  1246.         elif hasattr(object, "__module__"):
  1247.             # Maybe a class-like thing, in which case we care.
  1248.             if object.__module__ != module.__name__:
  1249.                 # Not the same module.
  1250.                 continue
  1251.             if not (hasattr(object, '__dict__')
  1252.                     and hasattr(object, '__bases__')):
  1253.                 # Not a class.
  1254.                 continue
  1255.  
  1256.             lineno = _extract_doctests(object.__dict__.items(),
  1257.                                        module,
  1258.                                        mdict,
  1259.                                        tests,
  1260.                                        prefix + name + ".")
  1261.             # XXX "-3" is unclear.
  1262.             _get_doctest(name, object, tests, prefix,
  1263.                          lineno="%s (or above)" % (lineno - 3))
  1264.  
  1265.     return minlineno
  1266.  
  1267. # Find all the doctests belonging to the module object.
  1268. # Return a list of
  1269. #     (testname, docstring, filename, lineno)
  1270. # tuples.
  1271.  
  1272. def _find_tests(module, prefix=None):
  1273.     if prefix is None:
  1274.         prefix = module.__name__
  1275.     mdict = module.__dict__
  1276.     tests = []
  1277.     # Get the module-level doctest (if any).
  1278.     _get_doctest(prefix, module, tests, '', lineno="1 (or above)")
  1279.     # Recursively search the module __dict__ for doctests.
  1280.     if prefix:
  1281.         prefix += "."
  1282.     _extract_doctests(mdict.items(), module, mdict, tests, prefix)
  1283.     return tests
  1284.  
  1285. # unittest helpers.
  1286.  
  1287. # A function passed to unittest, for unittest to drive.
  1288. # tester is doctest Tester instance.  doc is the docstring whose
  1289. # doctests are to be run.
  1290.  
  1291. def _utest(tester, name, doc, filename, lineno):
  1292.     import sys
  1293.     from StringIO import StringIO
  1294.  
  1295.     old = sys.stdout
  1296.     sys.stdout = new = StringIO()
  1297.     try:
  1298.         failures, tries = tester.runstring(doc, name)
  1299.     finally:
  1300.         sys.stdout = old
  1301.  
  1302.     if failures:
  1303.         msg = new.getvalue()
  1304.         lname = '.'.join(name.split('.')[-1:])
  1305.         if not lineno:
  1306.             lineno = "0 (don't know line number)"
  1307.         # Don't change this format!  It was designed so that Emacs can
  1308.         # parse it naturally.
  1309.         raise DocTestTestFailure('Failed doctest test for %s\n'
  1310.                                  '  File "%s", line %s, in %s\n\n%s' %
  1311.                                  (name, filename, lineno, lname, msg))
  1312.  
  1313. class DocTestTestFailure(Exception):
  1314.     """A doctest test failed"""
  1315.  
  1316. def DocTestSuite(module=None):
  1317.     """Convert doctest tests for a module to a unittest TestSuite.
  1318.  
  1319.     The returned TestSuite is to be run by the unittest framework, and
  1320.     runs each doctest in the module.  If any of the doctests fail,
  1321.     then the synthesized unit test fails, and an error is raised showing
  1322.     the name of the file containing the test and a (sometimes approximate)
  1323.     line number.
  1324.  
  1325.     The optional module argument provides the module to be tested.  It
  1326.     can be a module object or a (possibly dotted) module name.  If not
  1327.     specified, the module calling DocTestSuite() is used.
  1328.  
  1329.     Example (although note that unittest supplies many ways to use the
  1330.     TestSuite returned; see the unittest docs):
  1331.  
  1332.         import unittest
  1333.         import doctest
  1334.         import my_module_with_doctests
  1335.  
  1336.         suite = doctest.DocTestSuite(my_module_with_doctests)
  1337.         runner = unittest.TextTestRunner()
  1338.         runner.run(suite)
  1339.     """
  1340.  
  1341.     import unittest
  1342.  
  1343.     module = _normalize_module(module)
  1344.     tests = _find_tests(module)
  1345.     if not tests:
  1346.         raise ValueError(module, "has no tests")
  1347.  
  1348.     tests.sort()
  1349.     suite = unittest.TestSuite()
  1350.     tester = Tester(module)
  1351.     for name, doc, filename, lineno in tests:
  1352.         if not filename:
  1353.             filename = module.__file__
  1354.             if filename.endswith(".pyc"):
  1355.                 filename = filename[:-1]
  1356.             elif filename.endswith(".pyo"):
  1357.                 filename = filename[:-1]
  1358.         def runit(name=name, doc=doc, filename=filename, lineno=lineno):
  1359.             _utest(tester, name, doc, filename, lineno)
  1360.         suite.addTest(unittest.FunctionTestCase(
  1361.                                     runit,
  1362.                                     description="doctest of " + name))
  1363.     return suite
  1364.  
  1365. # Debugging support.
  1366.  
  1367. def _expect(expect):
  1368.     # Return the expected output (if any), formatted as a Python
  1369.     # comment block.
  1370.     if expect:
  1371.         expect = "\n# ".join(expect.split("\n"))
  1372.         expect = "\n# Expect:\n# %s" % expect
  1373.     return expect
  1374.  
  1375. def testsource(module, name):
  1376.     """Extract the doctest examples from a docstring.
  1377.  
  1378.     Provide the module (or dotted name of the module) containing the
  1379.     tests to be extracted, and the name (within the module) of the object
  1380.     with the docstring containing the tests to be extracted.
  1381.  
  1382.     The doctest examples are returned as a string containing Python
  1383.     code.  The expected output blocks in the examples are converted
  1384.     to Python comments.
  1385.     """
  1386.  
  1387.     module = _normalize_module(module)
  1388.     tests = _find_tests(module, "")
  1389.     test = [doc for (tname, doc, dummy, dummy) in tests
  1390.                 if tname == name]
  1391.     if not test:
  1392.         raise ValueError(name, "not found in tests")
  1393.     test = test[0]
  1394.     examples = [source + _expect(expect)
  1395.                 for source, expect, dummy in _extract_examples(test)]
  1396.     return '\n'.join(examples)
  1397.  
  1398. def debug(module, name):
  1399.     """Debug a single docstring containing doctests.
  1400.  
  1401.     Provide the module (or dotted name of the module) containing the
  1402.     docstring to be debugged, and the name (within the module) of the
  1403.     object with the docstring to be debugged.
  1404.  
  1405.     The doctest examples are extracted (see function testsource()),
  1406.     and written to a temp file.  The Python debugger (pdb) is then
  1407.     invoked on that file.
  1408.     """
  1409.  
  1410.     import os
  1411.     import pdb
  1412.     import tempfile
  1413.  
  1414.     module = _normalize_module(module)
  1415.     testsrc = testsource(module, name)
  1416.     srcfilename = tempfile.mktemp("doctestdebug.py")
  1417.     f = file(srcfilename, 'w')
  1418.     f.write(testsrc)
  1419.     f.close()
  1420.  
  1421.     globs = {}
  1422.     globs.update(module.__dict__)
  1423.     try:
  1424.         # Note that %r is vital here.  '%s' instead can, e.g., cause
  1425.         # backslashes to get treated as metacharacters on Windows.
  1426.         pdb.run("execfile(%r)" % srcfilename, globs, globs)
  1427.     finally:
  1428.         os.remove(srcfilename)
  1429.  
  1430.  
  1431.  
  1432. class _TestClass:
  1433.     """
  1434.     A pointless class, for sanity-checking of docstring testing.
  1435.  
  1436.     Methods:
  1437.         square()
  1438.         get()
  1439.  
  1440.     >>> _TestClass(13).get() + _TestClass(-12).get()
  1441.     1
  1442.     >>> hex(_TestClass(13).square().get())
  1443.     '0xa9'
  1444.     """
  1445.  
  1446.     def __init__(self, val):
  1447.         """val -> _TestClass object with associated value val.
  1448.  
  1449.         >>> t = _TestClass(123)
  1450.         >>> print t.get()
  1451.         123
  1452.         """
  1453.  
  1454.         self.val = val
  1455.  
  1456.     def square(self):
  1457.         """square() -> square TestClass's associated value
  1458.  
  1459.         >>> _TestClass(13).square().get()
  1460.         169
  1461.         """
  1462.  
  1463.         self.val = self.val ** 2
  1464.         return self
  1465.  
  1466.     def get(self):
  1467.         """get() -> return TestClass's associated value.
  1468.  
  1469.         >>> x = _TestClass(-42)
  1470.         >>> print x.get()
  1471.         -42
  1472.         """
  1473.  
  1474.         return self.val
  1475.  
  1476. __test__ = {"_TestClass": _TestClass,
  1477.             "string": r"""
  1478.                       Example of a string object, searched as-is.
  1479.                       >>> x = 1; y = 2
  1480.                       >>> x + y, x * y
  1481.                       (3, 2)
  1482.                       """,
  1483.             "bool-int equivalence": r"""
  1484.                                     In 2.2, boolean expressions displayed
  1485.                                     0 or 1.  By default, we still accept
  1486.                                     them.  This can be disabled by passing
  1487.                                     DONT_ACCEPT_TRUE_FOR_1 to the new
  1488.                                     optionflags argument.
  1489.                                     >>> 4 == 4
  1490.                                     1
  1491.                                     >>> 4 == 4
  1492.                                     True
  1493.                                     >>> 4 > 4
  1494.                                     0
  1495.                                     >>> 4 > 4
  1496.                                     False
  1497.                                     """,
  1498.            }
  1499.  
  1500. def _test():
  1501.     import doctest
  1502.     return doctest.testmod(doctest)
  1503.  
  1504. if __name__ == "__main__":
  1505.     _test()
  1506.